import store from './store/index'
import AppSceneUtil from './data/common/appScene';
import SessionUtil, {
  JxbHttpClient
} from './data/session/session';
import SystemUtil from './shell/system/system';
import SessionUserUtil from './data/session/sessionUser';
import SellingServerUtil from './data/sellingServer';
import SessionSellingServerUtil from './data/session/sessionSellingServer';
import InteractionUtil from './shell/ui/interaction';
/**
 * 为了后续的使用方便,不需要在每个页面import JxbHttpClient这个文件类,挂载到wx全局对象.在后面页面直接调用wx.$http()
 * 
 * @returns {JxbHttpClient}
 */
wx.$http = function () {
  return new JxbHttpClient()
}

App({
  data: {
    ApiUrl: 'https://' + store.data.requestDomain + '/', // 当前连接的服务器地址统一放到 /store/index.js 中配置
    pageSize1: 10,
    whitelist: [
      "pages/index/index"
    ]
  },
  onLaunch: function (options) {
    wx.removeStorage({
      key: 'position',
      success: function (res) {},
    })
    // 数据初始化
    SessionUtil.getInstance().then(session=>{
      console.log('app launch options.scene', options.scene, options)
      switch(options.scene){
        case 1037:
          let extraData = typeof options.referrerInfo.extraData !== 'undefined' ? options.referrerInfo.extraData : {};
          if(typeof extraData.token === 'string'){
            if(typeof extraData["3rdPartyId"] === 'undefined'){
              extraData["3rdPartyId"] = "";
            }
            // 登录
            JxbHttpClient.getClient().post({
              url: 'AppMaster/Login/wxAutoLoginByLoginToken',
              data:{
                token: session.token,
                login_token: extraData.token,
                "3rdPartyId": extraData["3rdPartyId"]
              }
            }).then(jxbResp=>{
              console.log('login with login token success', jxbResp)
              return Promise.all([SessionSellingServerUtil.renewCache(), SessionUserUtil.renewCache()])
            }).catch(err=>{
              console.log('login with login token failed', err)
              InteractionUtil.showNotice(err.message)
            })
          }
        break;
        default:
          // to nothing
      }
    })
    // this.getUserInfos();
    /**从分享点进来，获取分享的链接信息 */
    if (options.shareTicket) {
      wx.getShareInfo({
        shareTicket: options.shareTicket,
        success(data) {
          // res.errMsg; // 错误信息
          // res.encryptedData; // 解密后为一个 JSON 结构（openGId  群对当前小程序的唯一 ID）
          // res.iv; // 加密算法的初始向量
        },
      });
    }
    this.globalData.deviceInfo = SystemUtil.getSystemInfo(false)
  },
  is_need_seed_scene: false,
  onShow: function (options) {
    SessionUtil.getInstance().then(() => {
      AppSceneUtil.registerAppShowScene(options)
      this.is_need_seed_scene = options.scene;
    })
  },

  appState: (function () {
    var isShow = true;
    var getFlag = function () {
      var myShow = isShow;
      isShow = false;
      return myShow;
    }
    return {
      isShow: isShow,
      getFlag: getFlag
    }
  })(),
  call(phone) {
    phone = phone.replace(/-/g, '')
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  onHide() {
    wx.removeStorage({
      key: 'location',
      success: function (res) {},
    })
  },
  async getSaleMode() {
    let sessionUser = await SessionUserUtil.getInstance(), salesType = sessionUser.salesModelType,
      backgroundColorDic = {
        1: '#000000',
        2: '#650205',
        3: '#2a396a',
      };
    let bgColor = backgroundColorDic[sessionUser.salesModelType];
    if(typeof bgColor !== 'string') bgColor = backgroundColorDic[1];
    wx.setTabBarStyle({
      backgroundColor: bgColor
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: bgColor,
      animation: {
        duration: 10,
        timingFunc: 'easeIn'
      }
    })
    return salesType
  },
  /**
   * @deprecated 已废弃
   */
  globalData: {
    userInfo: {
      nickName: '',
      avatarUrl: ''
    },
    user: {},
    search: '',
    deviceInfo: {}
  },
  code: {
    code: '',
  }
})